package com.example.demo.controller;

import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.enums.ResultEnum;
import com.example.demo.service.UserService;
import com.example.demo.utils.EntityToDTO;
import com.example.demo.utils.StringUtil;
import com.example.demo.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/user")
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${web.upload-path}")
    private String uploadPath;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/login")
    public String login(String username, String password, String vcode, HttpSession session) throws SQLException {
       String code = (String) session.getAttribute("vcode");
       if (StringUtil.checkNull(vcode) || StringUtil.checkNull(username) || StringUtil.checkNull(password)) {
            return "redirect:/login.html";
       }
       if (!code.equalsIgnoreCase(vcode)){
           return "redirect:/login.html";
       }
       User user = userService.login(username,password);
       if (user == null ){
           return "redirect:/login.html";
       }
       if (username.equals(user.getUsername()) && password.equals(user.getUpassword())){
           session.setAttribute("user",user);
           return "redirect:/index.html";
       }
       return "redirect:/login.html";
    }

    @RequestMapping("/checkLogin")
    @ResponseBody
    public ResultVO checkLogin(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user == null){
            return new ResultVO(ResultEnum.DATA_NULL);
        }
        return  new ResultVO(ResultEnum.SUCCESS,user);
    }

    @RequestMapping("/findAllUser")
    @ResponseBody
    public ResultVO findAllUser(@RequestParam Map<String, String> map){
        int pageNum = Integer.valueOf(map.get("pageNum"));
        int rows = Integer.valueOf(map.get("rows"));
        int startNum = (pageNum - 1) * rows;
        List<User> lists = userService.findAllUser(startNum,rows);
        if (!lists.isEmpty()){
            List<UserDTO> userDTOList = EntityToDTO.EntiryListtoDTO(lists);
            return new ResultVO(ResultEnum.SUCCESS,userDTOList);
        }
        return new ResultVO(ResultEnum.DATA_NULL);
    }
    @RequestMapping("/findTotal")
    @ResponseBody
    public ResultVO findTotal(){
        int result = userService.findTotal();
        if (result >= 0){
            return new ResultVO(ResultEnum.SUCCESS,result);
        }
        return new ResultVO(ResultEnum.DATA_NULL);
    }

    @RequestMapping("/showToPage")
    @ResponseBody
    public ResultVO showToPage(int startNum,int rows){
        List<User> lists = userService.showToPage(startNum,rows);

        if (!lists.isEmpty()){
            List<UserDTO> userDTOList = EntityToDTO.EntiryListtoDTO(lists);
            return new ResultVO(ResultEnum.SUCCESS,userDTOList);
        }
        return  new ResultVO(ResultEnum.DATA_NULL);
    }
    @RequestMapping("/addUser")
    @ResponseBody
    public ResultVO addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, @RequestParam  Map<String,String> map, HttpServletResponse response) throws IOException {
        String uname = map.get("uname");
        String usex = map.get("usex");
        String uage = map.get("uage");
        String urole = map.get("urole");
        String imgPath = "";
        if (!file.isEmpty()){
            File savePos = new File(uploadPath);
            // 获取存放位置的规范路径
            String realPath = savePos.getCanonicalPath();
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID()+fileName;
            imgPath = realPath + "\\" +fileName;

            File dest = new File(imgPath);
            String path1 = uploadPath.substring(0,uploadPath.indexOf(":")+1);
            imgPath = imgPath.substring(imgPath.lastIndexOf(path1)+2);
            System.out.println(imgPath);
           // imgPath

            try{
                file.transferTo(dest);
                LOGGER.info("上传成功");
            } catch (IOException e){
                LOGGER.error(e.toString(), e);
            }
        }
        User user = new User(0,uname,"123456",imgPath,usex,Integer.valueOf(uage),Integer.valueOf(urole));
        boolean result = userService.addUser(user);
        return new ResultVO(ResultEnum.SUCCESS,result);
    }
    @RequestMapping("/updateUser")
    @ResponseBody
    public ResultVO updateUser(@RequestParam("myfile") MultipartFile file, HttpServletRequest request, @RequestParam  Map<String,String> map, HttpServletResponse response) throws IOException {
        String imgPath = "";
        Integer uid = Integer.valueOf(map.get("uid"));
        String uname = map.get("uname");
        String upassword = map.get("upassword");
        String usex = map.get("sel1");
        String uage = map.get("uage");
        String urole = map.get("sel2");
        if (!file.isEmpty()){
            File savePos = new File(uploadPath);
            // 获取存放位置的规范路径
            String realPath = savePos.getCanonicalPath();
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID()+fileName;
            imgPath = realPath + "\\" +fileName;
            File dest = new File(imgPath);
            String path1 = uploadPath.substring(0,uploadPath.indexOf(":")+1);
            imgPath = imgPath.substring(imgPath.lastIndexOf(path1)+2);
            System.out.println(imgPath);
            try{
                file.transferTo(dest);
                LOGGER.info("上传成功");
            } catch (IOException e){
                LOGGER.error(e.toString(), e);
            }
        }
        User user = new User(uid,uname,upassword,imgPath,usex,Integer.valueOf(uage),Integer.valueOf(urole));
        userService.updateUser(user);
        return new ResultVO(ResultEnum.SUCCESS,"上传成功");
    }
    @RequestMapping("/delUserByUid")
    @ResponseBody
    public ResultVO delUserByUid(String uid){
        int result = userService.delUserByUid(Integer.valueOf(uid));
        if (result > 0 ){
            return new ResultVO(ResultEnum.SUCCESS,result);
        }
        return new ResultVO(ResultEnum.ERROR,result);
    }

    @RequestMapping("/info")
    @ResponseBody
    public User info(String uid){
        User user = new User("zkr","666");
        return user;
    }
}
